// General WeChat Share function
// ===========================

;(function(global, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['wx'], factory)
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('wx'))
  } else {
    global.wxshare = factory(global.wx)
  }
})(this, function(wx) {
  var WxShare = {
    initShare: function(config, shareable, shareData) {
      var isDebug = location.search.indexOf('debug=true') > 0
      var apis = (shareable == false ? 'hideMenuItems' : ['onMenuShareTimeline', 'onMenuShareAppMessage'])
      that = this

      wx.config({
        debug: isDebug,
        appId: config.appid,
        timestamp: config.timestamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: apis
      })

      shareable == false ? that.hideMenu() : that.sharePage(shareData)

    },

    // hide all share menu
    hideMenu: function() {
      wx.ready(function() {
        wx.hideOptionMenu()
      })
    },

    // do config share with share data
    sharePage: function(shareData) {
      var that = this
      wx.ready(function() {
        wx.onMenuShareTimeline(that.getShareMessage(shareData))
        wx.onMenuShareAppMessage(that.getShareMessage(shareData))
      })
    },

    // return share message & success function
    getShareMessage: function(shareData) {
    
      return {
        title: shareData.name,
        desc:  shareData.desc,
        link:  shareData.link,
        imgUrl: __CTX__.cdn + '/' + shareData.cover,
        success: function() {
          $.ajax({
            type: 'POST',
            url: __CTX__.root + "/products/" + shareData.id + "/shared" ,
          }).done(function(result) {
            isDebug ? alert(result.messgae) : console.log(result);
          }).fail(function() {
            isDebug ? alert(result.message) : console.log(result);
          })
        }
      }
    }

  }

  return WxShare
})